'''
    Controller层
    主要负责接收客户端的请求
    响应数据
    提供API接口
'''
from fastapi import FastAPI, APIRouter, Depends
from sqlalchemy.orm import Session
from .stu_database import SessionLocal, Base, engine  # 加一个点表示当前目录
from .stu_crud import (
    get_stu_by_filters,  # 新增的多条件查询函数
    add_stu,
    get_id_stu
)
from . import stu_schema, stu_crud

# 创建所有数据表
Base.metadata.create_all(bind=engine)

app01 = APIRouter()

# 数据库会话依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app01.get("/students/", summary="查询学生信息（支持多条件筛选）")
async def query_students(
    student_id: int = None,
    student_name: str = None,
    class_name: str = None,  # 与模型保持一致，使用str类型
    db: Session = Depends(get_db)
):
    """
    支持按以下条件组合查询学生信息：
    - student_id: 学生编号（可选）
    - student_name: 学生姓名（可选）
    - class_name: 班级（可选）
    不填条件则返回所有学生
    """
    students = get_stu_by_filters(
        db,
        student_id=student_id,
        student_name=student_name,
        class_name=class_name
    )
    if not students:
        return {"message": "未找到符合条件的学生"}
    return students

# xiangmu/student/stu_controller.py（修改后）
@app01.post("/students/", summary="添加学生信息")
async def create_student(
    stu: stu_schema.Stu_schema,
    db: Session = Depends(get_db)
):
    """添加新学生，需提供完整学生信息"""
    # 检查学生是否已存在（get_id_stu已返回first()结果）
    existing_stu = get_id_stu(db, student_id=stu.student_id)
    if existing_stu:
        return {"message": f"学号为{stu.student_id}的学生已存在"}

    new_stu = add_stu(db, stu)
    return {
        "message": "学生信息添加成功",
        "student_id": new_stu.student_id,
        "student_name": new_stu.student_name
    }

@app01.put("/students/", summary="修改学生信息")
async def update_student(
    stu: stu_schema.Stu_schema,
    db: Session = Depends(get_db)
):
    existing_stu = get_id_stu(db, student_id=stu.student_id)
    if not existing_stu:
        return {"message": f"学号为{stu.student_id}的学生不存在"}

@app01.get("/students/over30/", summary="查询所有超过30岁的学员信息")
async def query_stu_over_30(db: Session = Depends(get_db)):
    students = stu_crud.get_stu_over_30(db)
    if students:
        return students
    return {"message": "无超过30岁的学员"}
    # return students if students else {"message": "无超过30岁的学员"}

@app01.get("/students/gender_count/", summary="统计每个班级男女生人数")
async def get_gender_count(db: Session = Depends(get_db)):
    return stu_crud.count_gender_by_class(db)